package net.scalan;

import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import net.scalan.jpa.PersistenceService;
import net.scalan.jpa.model.DBELink;
import net.scalan.jpa.model.DBStation;

/**
 *
 * @author scalan
 */
public class Main {

    private DBStation station;

    private List<ELinkScaner> scaners = new ArrayList<ELinkScaner>();

    public Main(long station_id) {
        EntityManager em = PersistenceService.getEntityManager();
        station = em.find(DBStation.class, station_id);
        if (station.getElinks() != null && station.getElinks().size() > 0) {
            for (DBELink elink : station.getElinks()) {
                ELinkScaner scaner = new ELinkScaner(elink);
                scaners.add(scaner);
                scaner.start();
            }
        }
        em.close();
    }

    private boolean workF = true;

    public void run() {
        if (station != null) {
            if (station.getElinks() != null && station.getElinks().size() > 0) {
                long n = 0;
                while (workF == true) {
                    System.out.println(">>> " + (++n));
                    if (scaners != null && scaners.size() > 0) {
                        for (ELinkScaner scaner : scaners) {
                            if (scaner != null) {
                                if (scaner.getStatus() == scaner.ST_PAUSE) {
                                    scaner.setStatus(scaner.ST_START);
                                }
                            }
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        System.err.println(ex);
                    }
                }
                if (n % 60 == 0) {
                    System.gc();
                }
            }
        } else {
            System.out.println("There are no any elinks on the station: '" + station.getName() + "'...");
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("CWM (cwm-can2db) module by ScAlAn A. Alex!!!");
        if (args != null && args.length == 1 && args[0] != null && args[0].length() > 0) {
            long station_id = Long.parseLong(args[0]);
            new Main(station_id).run();
        } else {
            System.out.println("Usage: Main <station_id>");
        }
    }
}
